package lwjglbase;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
import org.newdawn.slick.opengl.Texture;

public class LWJGLbase {

    //FPS stuff
    long prevTime; // Time since last frame
    int fps; //Frames per second
    long prevSecond; // Time that FPS was last reset
    //Textures
    Texture firstSprite;
    RoomBase currentLevel;
    
    static final String LEVELS_PATH = "levels/"; // Path to folder with level files
    static final String SPRITES_PATH = "sprites/"; // Path to folder with level files
    static final String MODELS_PATH = "models/"; // Path to folder with level files

    private long getTime() {
        return System.nanoTime() / 1000000;
    }

    private long getDelta() {
        long time = getTime();
        long delta = time - prevTime;
        prevTime = time;
        return delta;
    }

    private void updateFPS() {
        if (getTime() - prevSecond > 1000) {
            Display.setTitle("FPS:" + fps);
            fps = 0;
            prevSecond += 1000;
        }
        fps++;
    }

    protected void update(long delta) {
    }

    protected void draw(long delta) {
    }

    private void init() {
        prevTime = getTime();
        prevSecond = getTime();
        //Init Levels
        currentLevel = new Editor();
    }

    private void initDisplay() {
        try {
            Display.setDisplayMode(new DisplayMode(1200, 800));
            Display.create();
        } catch (LWJGLException e) {
            e.printStackTrace();
            System.exit(0);
        }
    }

    private void initGL() {
        glViewport(0, 0, Display.getWidth(), Display.getHeight());
        glMatrixMode(GL_PROJECTION); // init Projection matrix
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);// Init modelview matrix
        glLoadIdentity();
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_DEPTH_TEST);
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);
        glClearColor(.2f, .2f, .2f, 1);
    }

    private void gameLoop() {
        while (!Display.isCloseRequested()) { // Main loop
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            updateFPS();
            currentLevel.update(getDelta());
            currentLevel.draw(getDelta());
            Display.sync(60);
            Display.update();
        }
        cleanUp();
    }

    private void cleanUp() {
        Display.destroy();
    }

    public void start() {
        initDisplay();
        initGL();
        init();
        gameLoop();
        cleanUp();
    }

    public static void main(String[] args) {
        LWJGLbase l = new LWJGLbase();
        l.start();
    }
}
